<?php
/**
 * 应用自定义视图模板类
 * 
 * @version $Id: AppView.php 299 2012-05-09 08:18:45Z linsir123 $
 */
class AppView
{
	/**
	 * @var 是否爬虫访问
	 */
	static $isRobot = false;
	
	/**
	 * @var 是否IE6访问
	 */
	static $isIE6 = false;
	
	/**
	 * @var 相对路径
	 */
	static $domain;
	
	/**
	 * @var Css集合
	 */
	static $css;
	
	/**
	 * @var Javascript集合
	 */
	static $js;
	
	/**
	 * 初始化
	 */
	static function init()
	{
		static $__init = false;
		if ($__init) {
			return ;
		}
		$__init = true;
		
		///
		$view = App::getView();
		$engine = & $view->engine;
		
		self::$css = array('themes/css/layout%d.css', 'themes/default/style.css', 'themes/default/user.css');
		self::$js = array('_e35go/global.js');
		self::$domain = App::getRequest()->domain;
		
		/// 过滤器
		//$engine->registerFilter('pre', array('AppView', 'prefilter'));
		
		/// 动态模块
		$engine->registerPlugin('block', 'dynamic', 		array('AppView', 'dynamic'), false);
		
		/// 函数
		$engine->registerPlugin('function', 'JS', 			array('AppView', 'sDomJs'));
		$engine->registerPlugin('function', 'CSS', 			array('AppView', 'sDomCss'));
		$engine->registerPlugin('function', 'navTop', 		array('AppView', 'sNavTop'));
		$engine->registerPlugin('function', 'navSub', 		array('AppView', 'sNavSub'));
		$engine->registerPlugin('function', 'navHeader', 	array('AppView', 'sNavHeader'));
		$engine->registerPlugin('function', 'shopScore', 	array('AppView', 'sShopScore'));
		$engine->registerPlugin('function', 'itemInfo', 	array('AppView', 'sItemInfo'));
		$engine->registerPlugin('function', 'itemPrice', 	array('AppView', 'sItemPrice'));
		
		/* 链接相关 */
		$engine->registerPlugin('function', 'urlItem', 		array('AppView', 'urlItem'));
		$engine->registerPlugin('function', 'urlShop', 		array('AppView', 'urlShop'));
		$engine->registerPlugin('function', 'urlClass', 	array('AppView', 'urlClass'));
		$engine->registerPlugin('function', 'urlPhoto',		array('AppView', 'urlPhoto'));
	}
	
	/**
	 * 压缩html
	 */
	static function prefilter($content, & $smarty)
	{
		// 保护smarty标签将<-- {xxx} -->替换成 {xxx}
		$content = preg_replace('/<!--[^>|\n]*?({.+?})[^<|{|\n]*?-->/', '\1', $content);
		// 去掉html注释
		$content = preg_replace('/<!--.*?-->/', '', $content);
		// 压缩html代码,去掉行首尾空格及换行
		return preg_replace("/\s*[\n\r]+\s*/", '', $content);
	}
	
	/**
	 * 动态内容
	 */
	static function dynamic($param, $content)
	{
		return $content;
	}
	
	/**
	 * 添加Css
	 */
	static function addCss($css)
	{
		array_push(self::$css, $css);
	}
	
	/**
	 * 添加Javascript
	 */
	static function addJs($js)
	{
		array_push(self::$js, $js);
	}
	
	/**
	 * 连接 - 商品
	 */
	static function urlItem($params = null)
	{
		$route = 'item/'.$params['iid'];
		return lpUrl::__($route);
	}
	
	/**
	 * 连接 - 商店
	 */
	static function urlShop($params = null)
	{
		$cid = intval($params['cid']);
		$route = 'shop/'.$params['nick'].'/';
		$route .= self::_routeCreate($params);
		
		///
		return lpUrl::__($route);
	}
	
	/**
	 * 连接 - 分类
	 */
	static function urlClass($params = null)
	{
		if ( ! isset($params['pinyin'])) {
			$cid = intval($params['cid']);
			$nav = M::nav()->getOne($cid);
			$pinyin = $nav['pinyin'];
		} else 
			$pinyin = $params['pinyin'];
			
		///
		$route = 'list/'.$pinyin.'/'.self::_routeCreate($params);
		return lpUrl::__($route);
	}
	
	/**
	 * 淘宝图片“伪本地地址”
	 * // 将爬虫访问时的,图片全切换为本地图片
	 */
	static function urlPhoto($params)
	{
		if (self::$isRobot) 
			return App::getRequest()->domain.'images/calendar.gif';
			
		///
		if ($url = trim($params['url'])) {
			$pattern = "/http:\/\/(.*)\.taobaocdn\.com\/bao\/uploaded\/(.*)/";
			if (preg_match($pattern, $url, $m)) {
				// $key = 'item'; 
				// $url = $m[1]."@@".$m[2];
				
				return $url;
			} else {
				// $key = 'shop';
				
				return 'http://logo.taobaocdn.com/shop-logo'.$url;
			}
				
			return lpUrl::__('photo/'.$key.'/'.base64_encode($url));
		} else 
			return false;
	}
	
	/**
	 * 导航列表 - 头部
	 */
	static function sNavHeader()
	{
		$content = '';
		$navs = App::O('_nav.header');
		foreach ($navs as $key => $v) {
			$href = lpUrl::__('goto/channel/'.$key);
			$content .= '<a target="_blank" href="'.$href.'">'.$v[0].'</a>';
		}
			
		return '<div class="link">频道推荐：'
			.$content.'</div>';
	}
	
	/**
	 * 导航列表 - 一级
	 */
	static function sNavTop($params = null)
	{
		$mNav = M::nav();
		$cId = intval($params['cid']);
		$nav = $mNav->getOne($cId);
			
		///
		$content = '';
		$navHover = false;
		$navs = $mNav->getAll();
		foreach ($navs as $id => $v) {
			if ( ! isset($v['show']) || empty($v['show'])) 
				continue;
				
			if ($nav['id'] == $id || $nav['pid'] == $id) {
				$hover = 'class="navhover"';
				$navHover = true;
			} else 
				$hover = '';
				
			$title = $v['title'];
			$href = self::urlClass(array('cid'=>$id));
			$content .= '<li '.$hover.'><a href="'.$href.'" title="'.$title.'">'.$title.'</a></li><li class="liImg"></li>';
		}
		
		///
		$navs = App::O('_nav.top2');
		return self::_navFormat($navs['prefix'], $params['menu'], $navHover).$content
			.self::_navFormat($navs['suffix'], $params['menu'], $navHover);
	}
	
	/**
	 * 导航列表 - 二级
	 */
	static function sNavSub($params = null)
	{
		$mNav = M::nav();
		$cId = intval($params['cid']);
		$nav = $mNav->getOne($cId);
		if ($nav['pid'] == 0) 
			$navs = $mNav->getSub($cId);
		else 
			$navs = $mNav->getSub($nav['pid']);
			
		///
		$content = '';
		foreach ($navs as $id => $title) {
			$href = self::urlClass(array('cid'=>$id));
			$hover = $nav['id'] == $id ? 'class="submenu_cur"' : '';
			$content .= '<a '.$hover.' href="'.$href.'" title="'.$title.'">'.$title.'</a>';
		}
		
		if ($content) 
			return '<div class="content submenu clearfix">'.$content.'</div>';
		else 
			return ;
	}
	
	/**
	 * 店铺积分
	 */
	static function sShopScore($params = null)
	{
		$score = floatval($params['score']);
		$score = intval($score*10);
		for ($i=50; $i>0; $i-=5) {
			if ($score >= $i) {
				$score = $i;
				break;
			}
		}
		
		return '<img src="' . self::$domain.'images/score/'.$score.'.gif" width="60" height="12" />&nbsp;'.$params['score'];
	}
	
	/**
	 * 商品信息明细
	 * // 区分IE6
	 */
	static function sItemInfo($params = null)
	{
		$Iid = $params['iid'];
		/*
		if (self::$isIE6) {
			$domain = App::getRequest()->domain;
			$convert = M::item()->getTaobaoke($Iid);
			return '<div style="line-height: 45px;font-size: 14px;"><p>如果您想了解商品的详细信息，请点击：'
				. '<script type="text/javascript">document.writeln("<a class=\"btnBuy\" target=\"_blank\" href=\""+"'.$convert['click_url'].'"+uId+"\">"+"<img src=\"'.$domain.'images/toitem.gif\" />"+"</a>");</script></p>'
				. '<p style="color: #FF0000;">本站所有商品交易均在淘宝网（www.taobao.com）上进行，以免上当受骗！</p></div>';
		}
		*/
		$item = M::item()->getInfo($Iid);
		return preg_replace("/(?<=href=)([^\>]*)(?=\>)/i","#", $item['desc']);
	}
	
	/**
	 * 商品返利
	 */
	static function sItemPrice($params = null)
	{
		static $rate;
		if ( ! isset($rate)) 
			$rate = App::O('taobaoke.rate');
			
		///
		$price = floatval($params['price']);
		$len = intval($params['len']);
		if (empty($len)) 
			$len = 2;
			
		///
		return sprintf("￥%.{$len}f", $rate*$price);
	}
	
	/**
	 * Css
	 */
	static function sDomCss($params = null)
	{
		$layout = intval($params['layout']);
		if (empty($layout)) 
			$layout = 2;
			
		self::$css[0] = sprintf(self::$css[0], $layout);
		
		///
		if (strlen(self::$domain)==1) 
			$b = '';
		else {
			$b = substr(self::$domain, 1);
			$b = substr($b, 0, strlen($b)-1);
			$b = 'b='.$b.'&amp;';
		}
		$content = '<link type="text/css" rel="stylesheet" href="';
		$content .= self::$domain.'min/'.$b.'f='.implode(',', self::$css);
		$content .= '" />';
		return $content;
	}
	
	/**
	 * Javascript
	 */
	static function sDomJs($params = null)
	{
		$content = '<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.6.2/jquery.min.js"></script>';
		$content .= "\r\n";
		$content .= '<script type="text/javascript">if(!window.jQuery){document.write(\'<script type="text/javascript" src="'.self::$domain.'javascript/jquery-1.6.2.min.js"><\/script>\');}</script>';
		$content .= "\r\n";
		
		///
		$content .= '<script type="text/javascript" src="';
		$content .= self::$domain.'min/b='.substr(self::$domain, 1).'javascript&amp;f='.implode(',', self::$js);
		$content .= '"></script>';
		///
		
		return $content;
	}
	
	
	/// 
	
	
	/**
	 * 格式化一级导航
	 */
	static function _navFormat($navs, $menu, $navHover = false)
	{
		$content = '';
		foreach ($navs as $title => $nav) {
			$href = lpUrl::__($nav['r']);
			$hover = ( ! $navHover && in_array($menu, $nav['hover'])) ? 'class="navhover"' : '';
			$content .= '<li '.$hover.'><a href="'.$href.'" title="'.$title.'">'.$title.'</a></li><li class="liImg"></li>';
		}
		
		return $content;
	}
	
	/**
	 * 创建路由
	 */
	static function _routeCreate($params)
	{
		/// 分类ID
		$route = ( ! empty($params['cid']) ? $params['cid'] : '0').'-';
		
		/// 关键字
		$route .= ( ! empty($params['keyword']) ? $params['keyword'] : '0').'-';
		
		/// 价格区间
		$route .= ( ! empty($params['start_price']) ? $params['start_price'] : '0').'-';
		$route .= ( ! empty($params['end_price']) ? $params['end_price'] : '0').'-';
		
		/// 排序
		$route .= ( ! empty($params['sort']) ? $params['sort'] : '0').'-';
		
		/// 默认页码
		$route .= ( ! empty($params['p']) ? $params['p'] : '1');
		return $route;
	}
}
